<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Higher Order Comp</title>
    </head>
    <body>
        <script src="../dist/vue-2.6.14.js"></script>

        <div id="app">
            <smart-avatar username="hello"></smart-avatar>
            <smart-avatar2 username="hello"></smart-avatar2>
        </div>

        <script>
            const Avatar = {
                name: 'Avatar',
                props: ['url'],
                template: `<img :src="url" style="max-width: 150px;">`,
            };

            function fetchURL(username, cb) {
                setTimeout(() => {
                    cb('https://vuejs.org/images/logo.svg');
                }, 500);
            }

            function withUsernameAvatar(innerComponent, defaultURL) {
                return {
                    props: ['username'],
                    data() {
                        return {
                            url:
                                defaultURL || 'https://via.placeholder.com/150',
                        };
                    },
                    created() {
                        fetchURL(this.username, (url) => {
                            this.url = url;
                        });
                    },
                    render(h) {
                        return h(innerComponent, {
                            props: {
                                url: this.url,
                            },
                        });
                    },
                };
            }

            const SmartAvatar = withUsernameAvatar(Avatar);
            Vue.component('smart-avatar', SmartAvatar);

            const SmartAvatar2 = withUsernameAvatar(
                Avatar,
                'https://cn.vitejs.dev/logo.svg'
            );
            Vue.component('smart-avatar2', SmartAvatar2);

            new Vue({ el: '#app' });
        </script>
    </body>
</html>
